package com.freedom.shiro;

import com.freedom.sys.SerializableUtils;
import com.freedom.util.sys.RedisUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class RedisSessionDao extends MySessionDao {

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        RedisUtil.set(sessionId.toString(), SerializableUtils.serialize(session));
        return session.getId();
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Object obj = RedisUtil.get(sessionId.toString());
        return SerializableUtils.deserialize(obj.toString());
    }

    @Override
    protected void doUpdate(Session session) {
        if (session instanceof ValidatingSession && !((ValidatingSession) session).isValid()) {
            return;
        }
        RedisUtil.set(session.getId().toString(), SerializableUtils.serialize(session));
    }

    @Override
    protected void doDelete(Session session) {
        RedisUtil.remove(session.getId().toString());
    }
}
